package com.foodchain.service;

import com.foodchain.consts.Consts;
import com.foodchain.entity.Activity;
import com.foodchain.entity.ActivityUser;
import com.foodchain.repository.ActivityRepository;
import com.foodchain.repository.ActivityUserRepository;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.persistence.criteria.*;
import java.util.Date;

/**
 * @ClassName ActivityUserService
 * @Description TODO
 * @Author duyuanyuan
 * @Date 2019/3/13 13:47
 * @Version 1.0
 **/
@Service
public class ActivityUserService {

    @Resource
    private ActivityUserRepository repository;

    @Resource
    private ActivityRepository activityRepository;

    public void saveApplyUser(ActivityUser activityUser) {
        Activity one = activityRepository.getOne(activityUser.getActivityId());
        activityUser.setActivityName(one.getActivityName());
        activityUser.setActivityImg(one.getActivityImg());
        activityUser.setCreateTime(new Date());
         activityUser.setUserStatus(0);
         activityUser.setClassify(one.getClassify());
        repository.saveAndFlush(activityUser);
    }

    public Page<ActivityUser> findByUserId(String userId, Integer page, Integer size) {
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.DESC, "createTime");
        Specification<ActivityUser> spec = new Specification<ActivityUser>() {        //查询条件构造
            public Predicate toPredicate(Root<ActivityUser> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Path<Boolean> userid= root.get("userId");
                Predicate p1 = cb.equal(userid,userId);
                Predicate p = cb.and(p1);
                return p;
            }
        };
        Page<ActivityUser> all = repository.findAll(spec, pageable);
        for(ActivityUser activityUser:all){
            activityUser.setActivityImg(Consts.FileUrl.file_url+"/"+activityUser.getActivityImg());
        }
        return all;
    }

    public ActivityUser findByUserIdAndActivityId(ActivityUser activityUser) {
        return repository.findByUserIdAndActivityId(activityUser.getUserPhone(),activityUser.getActivityId());
    }
}
